package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/9/9 9:35
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有秒杀商品列表
     * @return
     */
    @GetMapping("findAll")
    public Result findAll(){
        //  调用服务层方法
        List<SeckillGoods> seckillGoodsList = this.seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    /**
     * 秒杀商品详情
     * @param skuId
     * @return
     */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        //  调用服务层方法
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    /**
     * 生成抢购码
     * @param skuId
     * @return
     */
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取到当前秒杀对象
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        if (null != seckillGoods){
            //  要在秒杀开始之后，结束之前生成抢购码
            Date currentTime = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime)&& DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  此时生成抢购码
                //  MD5.encrypt(userId+skuId);
                //  MD5.encrypt(userId);
                String skuIdStr = MD5.encrypt(userId + skuId);
                //  返回抢购码
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成抢购码失败.");
    }

    //  /auth/seckillOrder/' + skuId + '?skuIdStr=' + skuIdStr

    /**
     * 预下单控制器
     * @param skuId
     * @param request
     * @return
     */
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取到前端传递的抢购码：
        String skuIdStr = request.getParameter("skuIdStr");
        //  调用服务层方法
        return this.seckillGoodsService.seckillOrder(skuId,userId,skuIdStr);
    }

    //  /auth/checkOrder/

    /**
     * 检查秒杀状态.
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  返回数据
        return this.seckillGoodsService.checkOrder(skuId,userId);
    }

    /**
     * 秒杀订单确认页面渲染需要参数汇总接口
     * @return
     */
    @GetMapping("/auth/trade")
    public Result<Map<String,Object>> trade(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法
        Map<String,Object> map = this.seckillGoodsService.trade(userId);
        return Result.ok(map);
    }

    //  保存秒杀订单.
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //  调用方法，返回订单Id
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        //  判断
        if (null == orderId) {
            return Result.fail().message("远程调用保存订单失败.");
        }
        //  删除预下单记录 hdel key field
        this.redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS,userId);
        //  保存一份数据到缓存
        this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS,userId,orderId.toString());
        //  返回订单Id
        return Result.ok(orderId);
    }
}
